package com.moxiao.yfjh.module.blind.controller.app.controller.exchage;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.util.date.DateUtils;
import com.moxiao.yfjh.framework.dict.core.util.DictFrameworkUtils;
import com.moxiao.yfjh.framework.ip.core.utils.AreaUtils;
import com.moxiao.yfjh.module.blind.common.BlindDictTypeConstants;
import com.moxiao.yfjh.module.blind.common.BlindNotifyMessageUtils;
import com.moxiao.yfjh.module.blind.common.JgPushSend;
import com.moxiao.yfjh.module.blind.common.MemberUserEnumUtil;
import com.moxiao.yfjh.module.blind.controller.admin.constellationtest.vo.ConstellationTestExportReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.equity.vo.MemberEquityCreateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberLike.vo.MemberLikeCreateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberLike.vo.MemberLikeUpdateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSayHello.vo.MemberSayhelloCreateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSayHello.vo.MemberSayhelloUpdateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSeeme.vo.MemberSeemeCreateReqVO;
import com.moxiao.yfjh.module.blind.controller.admin.memberSeeme.vo.MemberSeemeUpdateReqVO;
import com.moxiao.yfjh.module.blind.controller.app.controller.exchage.vo.*;
import com.moxiao.yfjh.module.blind.controller.app.convert.MemberExchangeConvert;
import com.moxiao.yfjh.module.blind.dal.dataobject.basicSetting.BlindBasicSettingDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.constellationtest.ConstellationTestDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.memberLike.MemberLikeDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.memberSayHello.MemberSayhelloDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.memberSeeme.MemberSeemeDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.privilege.MemberPrivilegeDO;
import com.moxiao.yfjh.module.blind.service.album.BlindMemberAlbumService;
import com.moxiao.yfjh.module.blind.service.basicSetting.BlindBasicSettingService;
import com.moxiao.yfjh.module.blind.service.constellationtest.ConstellationTestService;
import com.moxiao.yfjh.module.blind.service.equity.MemberEquityService;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.memberLike.MemberLikeService;
import com.moxiao.yfjh.module.blind.service.memberSayHello.MemberSayhelloService;
import com.moxiao.yfjh.module.blind.service.memberSeeme.MemberSeemeService;
import com.moxiao.yfjh.module.blind.service.moment.BlindMemberMomentService;
import com.moxiao.yfjh.module.blind.service.privilege.MemberPrivilegeService;
import com.moxiao.yfjh.module.maker.service.MemberStringingApiService;
import com.moxiao.yfjh.module.system.mq.kafka.KafkaProducer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.*;
import static com.moxiao.yfjh.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static com.moxiao.yfjh.module.blind.enums.ErrorCodeConstants.*;

/**
 * @version 1.0
 * @Author zhk
 * @Date 2024/1/15 11:42
 **/
@Tag(name = "app - 相亲交友-交流")
@RestController
@RequestMapping("/blind/member-exchange")
@Validated
@Slf4j
public class MemberExchangeController {

    @Resource
    private BlindMemberUserService blindMemberUserService;
    @Resource
    private MemberSayhelloService memberSayhelloService;
    @Resource
    private MemberSeemeService memberSeemeService;
    @Resource
    private MemberLikeService memberLikeService;
    @Resource
    private BlindMemberMomentService blindMemberMomentService;
    @Resource
    private BlindMemberAlbumService blindMemberAlbumService;
    @Resource
    private BlindBasicSettingService blindBasicSettingService;

    @Resource
    private MemberEquityService memberEquityService;

    @Resource
    private MemberPrivilegeService memberPrivilegeService;

    @Resource
    private BlindNotifyMessageUtils blindNotifyMessageUtils;
    @Resource
    private MemberStringingApiService memberStringingApiService;
    @Autowired
    private KafkaProducer kafkaProducer;
    @Resource
    private ConstellationTestService constellationTestService;
    @Resource
    private JgPushSend jgPushSend;

    @GetMapping("/isSueSayHelloList")
    @Operation(summary = "发出的打招呼列表信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getIsSueSayHelloList(@RequestParam("haveMember") Integer haveMember) {
        String loginUserId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginUserId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberSayhelloReqVO appMemberSayhelloReqVO = new AppMemberSayhelloReqVO();
        appMemberSayhelloReqVO.setIssue(loginUserId);
        appMemberSayhelloReqVO.setHaveMember(haveMember);
        List<MemberSayhelloDO> memberSayhelloList = memberSayhelloService.getMemberSayhelloList(appMemberSayhelloReqVO);
        List<AppMemberExchangeReqVO> appMemberExchangeReqVOS = MemberExchangeConvert.INSTANCE.convertSayHello(memberSayhelloList);
        return CommonResult.success(suppleMemberInformation(appMemberExchangeReqVOS, "0", loginUserId, haveMember));
    }

    @GetMapping("/receiveSayHelloList")
    @Operation(summary = "收到的打招呼列表信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getReceiveSayHelloList(@RequestParam("haveMember") Integer haveMember) {
        String loginId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberSayhelloReqVO appMemberSayhelloReqVO = new AppMemberSayhelloReqVO();
        appMemberSayhelloReqVO.setReceive(loginId);
        appMemberSayhelloReqVO.setHaveMember(haveMember);
        List<MemberSayhelloDO> memberSayhelloList = memberSayhelloService.getMemberSayhelloList(appMemberSayhelloReqVO);
        List<AppMemberExchangeReqVO> appMemberExchangeReqVOS = MemberExchangeConvert.INSTANCE.convertSayHello(memberSayhelloList);
        return CommonResult.success(suppleMemberInformation(appMemberExchangeReqVOS, "0", loginId, haveMember));
    }

    @PostMapping("/whetherOrNotSayHello")
    @Operation(summary = "是否打过打招呼")
    public CommonResult<Boolean> whetherOrNotSayHello(@Valid @RequestBody MemberSayhelloCreateReqVO createReqVO) {
        Long loginUserId = getLoginUserId();
        if (Objects.isNull(loginUserId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberSayhelloReqVO appMemberSayhelloReqVO = new AppMemberSayhelloReqVO();
        appMemberSayhelloReqVO.setIssue(createReqVO.getIssue());
        appMemberSayhelloReqVO.setReceive(createReqVO.getReceive());
        MemberSayhelloDO blindMemberSayHello = memberSayhelloService.getBlindMemberSayHello(appMemberSayhelloReqVO);
        // 获得打招呼的次数
        if (getForceNum()) {
            if (Objects.isNull(blindMemberSayHello)){
                return success(Boolean.TRUE);
            }
            if (Objects.equals(loginUserId, Long.valueOf(blindMemberSayHello.getIssue()))) {
                return error(MEMBER_NOT_CANNOT_BE_REPEATED_EXISTS.getCode(), MEMBER_NOT_CANNOT_BE_REPEATED_EXISTS.getMsg());
            } else {
                return success(Boolean.TRUE);
            }
        } else {
            return buildSuccess(Boolean.FALSE, SAY_HELLO_NUM.getMsg());
        }
    }

    @PostMapping("/createBlindMemberSayHello")
    @Operation(summary = "创建相亲会员打招呼")
    public CommonResult<AppExchangeReqVo> createBlindMemberSayHello(@Valid @RequestBody MemberSayhelloCreateReqVO createReqVO) {
        long startTime = System.nanoTime();
        log.error("会员打招呼开始{},", startTime);
        // 是否是会员验证
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO login = blindMemberUserService.getMemberUser(loginUserId);
        if (Objects.isNull(login)) {
            return error(401, "获取个人信息失败");
        } else {

            if (Objects.equals(login.getHaveMember(), (byte) 0)) {
                throw exception(MEMBER_FORCE_PAIRING_NOT_EXISTS);
            }

            if (StringUtils.isEmpty(createReqVO.getContent())) {
                throw exception(MEMBER_USER_SA_HELLO_NOT_EXISTS);
            }

            BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(Long.valueOf(createReqVO.getReceive()));
            if (Objects.isNull(memberUser)){
                return error(401, "获取打招呼人的信息失败");
            }

            AppMemberSayhelloReqVO appMemberSayhelloReqVO = new AppMemberSayhelloReqVO();
            appMemberSayhelloReqVO.setIssue(createReqVO.getIssue());
            appMemberSayhelloReqVO.setReceive(createReqVO.getReceive());
            MemberSayhelloDO blindMemberSayHello = memberSayhelloService.getBlindMemberSayHello(appMemberSayhelloReqVO);
            if (Objects.nonNull(blindMemberSayHello)) {
                // kafka 打招呼-生产消息发送
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("content", createReqVO.getContent());
                jsonObject.addProperty("backContent", createReqVO.getBackContent());
                jsonObject.addProperty("id", blindMemberSayHello.getId());
                jsonObject.addProperty("receive", createReqVO.getReceive());
                jsonObject.addProperty("issue", createReqVO.getIssue());

                kafkaProducer.addSendSayHello(jsonObject);
                MemberSayhelloUpdateReqVO updateReqVO = new MemberSayhelloUpdateReqVO();
                updateReqVO.setId(blindMemberSayHello.getId());
                updateReqVO.setSayHello((byte) 1);
                updateReqVO.setStatus((byte) 1);
                memberSayhelloService.updateMemberSayhello(updateReqVO);

                AppExchangeReqVo appExchangeReqVo = new AppExchangeReqVo();
                if (Objects.equals(Long.valueOf(createReqVO.getReceive()), loginUserId)) {
                    appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getIssue()));
                } else {
                    appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getReceive()));
                }
                appExchangeReqVo.setEachOther((byte) 1);
                appExchangeReqVo.setMatchAge(memberUser.getAge());
                appExchangeReqVo.setMatchNickName(memberUser.getNickname());
                appExchangeReqVo.setMatchAvatar(memberUser.getAvatar());
                appExchangeReqVo.setOwnAvatar(login.getAvatar());

                long endTime = System.nanoTime();
                long duration = (endTime - startTime);  // 纳秒级别
                double seconds = (double) duration / 1_000_000_000.0; // 转换为秒

                log.error("打招呼结束，当前时间：{}秒", seconds);
                return success(appExchangeReqVo);
            }

            MemberEquityCreateReqVO memberEquityCreateReqVO = new MemberEquityCreateReqVO();
            memberEquityCreateReqVO.setUserId(getLoginUserId());
            memberEquityCreateReqVO.setEquityName("打招呼");
            memberEquityCreateReqVO.setUsedBy(createReqVO.getIssue());
            memberEquityService.createMemberEquity(memberEquityCreateReqVO);
            String content = createReqVO.getContent();
            String backContent = createReqVO.getBackContent();
            createReqVO.setBackContent("正在回复打招呼......");
            createReqVO.setContent("正在打招呼......");

            Long memberSayhello = memberSayhelloService.createMemberSayhello(createReqVO);
            //  kafka 打招呼-生产消息发送
            JsonObject jsonObject = new JsonObject();
            if (StringUtils.isNotEmpty(backContent)) {
                jsonObject.addProperty("backContent", backContent);
            } else {
                jsonObject.addProperty("backContent", "       ");
            }
            jsonObject.addProperty("content", content);
            jsonObject.addProperty("id", memberSayhello);
            jsonObject.addProperty("receive", createReqVO.getReceive());
            jsonObject.addProperty("issue", createReqVO.getIssue());
            kafkaProducer.addSendSayHello(jsonObject);
            AppExchangeReqVo appExchangeReqVo = new AppExchangeReqVo();
            if (Objects.equals(Long.valueOf(createReqVO.getReceive()), loginUserId)) {
                appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getIssue()));
            } else {
                appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getReceive()));
            }
            appExchangeReqVo.setEachOther((byte) 0);

            if (Objects.nonNull(memberSayhello)) {
                blindNotifyMessageUtils.createSayHelloMessage(createReqVO);
            }

            long endTime = System.nanoTime();
            long duration = (endTime - startTime);  // 纳秒级别
            double seconds = (double) duration / 1_000_000_000.0; // 转换为秒
            log.error("方法执行结束，当前时间：{}秒", seconds);
            return success(appExchangeReqVo);
        }
    }


    @GetMapping("/getIsSueSeeMeList")
    @Operation(summary = "发出的看过我的信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getIsSueSeeMeList(@RequestParam("haveMember") Integer haveMember) {
        String loginId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberSeemeReqVO appMemberSeemeReqVO = new AppMemberSeemeReqVO();
        appMemberSeemeReqVO.setIssue(loginId);
        appMemberSeemeReqVO.setHaveMember(haveMember);
        List<MemberSeemeDO> memberSeeMeDOS = memberSeemeService.getMemberSeemeList(appMemberSeemeReqVO);
        List<AppMemberExchangeReqVO> appMemberExchangeReqVOS = MemberExchangeConvert.INSTANCE.convertMemberSeeMe(memberSeeMeDOS);
        return CommonResult.success(suppleMemberInformation(appMemberExchangeReqVOS, "1", loginId, haveMember));
    }


    @GetMapping("/getReceiveSeeMeList")
    @Operation(summary = "收到的看过我列表信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getReceiveSeeMeList(@RequestParam("haveMember") Integer haveMember) {
        String loginId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberSeemeReqVO appMemberSeemeReqVO = new AppMemberSeemeReqVO();
        appMemberSeemeReqVO.setReceive(loginId);
        appMemberSeemeReqVO.setHaveMember(haveMember);
        List<MemberSeemeDO> memberSeeMeDOS = memberSeemeService.getMemberSeemeList(appMemberSeemeReqVO);
        List<AppMemberExchangeReqVO> appMemberExchangeReqVOS = MemberExchangeConvert.INSTANCE.convertMemberSeeMe(memberSeeMeDOS);
        return CommonResult.success(suppleMemberInformation(appMemberExchangeReqVOS, "1", loginId, haveMember));
    }


    @PostMapping("/createBlindMemberSeeMe")
    @Operation(summary = "创建相亲会员看过我")
    public CommonResult<Long> createBlindMemberSeeMe(@Valid @RequestBody MemberSeemeCreateReqVO createReqVO) {
        if (Objects.equals(createReqVO.getIssue(), createReqVO.getReceive())) {
            return success(0L);
        }
        MemberSeemeDO memberSeeme = memberSeemeService.getMemberSeeme(createReqVO.getIssue(), createReqVO.getReceive());
        if (Objects.nonNull(memberSeeme)) {
            MemberSeemeUpdateReqVO updateReqVO = new MemberSeemeUpdateReqVO();
            updateReqVO.setId(memberSeeme.getId());
            Long num = memberSeeme.getNum() + 1;
            updateReqVO.setNum(num);
            memberSeemeService.updateMemberSeeme(updateReqVO);
            return success(memberSeeme.getId());
        }
        return success(memberSeemeService.createMemberSeeme(createReqVO));
    }


    @GetMapping("/isSueLikeList")
    @Operation(summary = "发出的喜欢我列表信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getIsSueLikeList(@RequestParam("haveMember") Integer haveMember) {
        String loginUserId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginUserId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberLikeReqVO appMemberLikeReqVO = new AppMemberLikeReqVO();
        appMemberLikeReqVO.setIssue(loginUserId);
        appMemberLikeReqVO.setHaveMember(haveMember);
        List<MemberLikeDO> memberLikeList = memberLikeService.getMemberLikeList(appMemberLikeReqVO);
        return CommonResult.success(
                suppleMemberInformation(MemberExchangeConvert.INSTANCE.convertMemberLike(memberLikeList), "0", loginUserId, haveMember));
    }

    @GetMapping("/receiveLikeList")
    @Operation(summary = "收到的喜欢我列表信息")
    @Parameter(name = "haveMember", description = "是否是会员", required = true)
    public CommonResult<List<AppMemberExchangeReqVO>> getReceiveLikeList(@RequestParam("haveMember") Integer haveMember) {
        String loginId = String.valueOf(getLoginUserId());
        if (StringUtils.isEmpty(loginId)) {
            return error(401, "获取用户信息失败");
        }
        AppMemberLikeReqVO appMemberLikeReqVO = new AppMemberLikeReqVO();
        appMemberLikeReqVO.setReceive(loginId);
        appMemberLikeReqVO.setHaveMember(haveMember);
        List<MemberLikeDO> memberLikeList = memberLikeService.getMemberLikeList(appMemberLikeReqVO);
        List<AppMemberExchangeReqVO> appMemberExchangeReqVOS = MemberExchangeConvert.INSTANCE.convertMemberLike(memberLikeList);
        return CommonResult.success(suppleMemberInformation(appMemberExchangeReqVOS, "0", loginId, haveMember));
    }


    @PostMapping("/createBlindMemberLike")
    @Operation(summary = "创建相亲会员喜欢我")
    public CommonResult<AppExchangeReqVo> createBlindMemberLike(@Valid @RequestBody MemberLikeCreateReqVO createReqVO) {
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(getLoginUserId());
        if (Objects.isNull(memberUser)) {
            return error(401, "获取个人信息失败");
        }
        if (Objects.equals(createReqVO.getHaveMember(), (byte) 0)) {
            BlindBasicSettingDO basicSetting = blindBasicSettingService.getBasicSetting(1L);
            Long todayLikeNum = memberLikeService.getMemberLikeByUserId(DateUtils.getTodayStart(), DateUtils.getTodayEnd(), String.valueOf(getLoginUserId()));
            if (todayLikeNum >= Long.valueOf(basicSetting.getLikeNum())) {
                throw exception(MEMBER_Like_NOT_EXISTS);
            }
        } else {
            MemberPrivilegeDO memberPrivilege;
            if (Objects.equals(memberUser.getUserLevel(), (byte) 1)) {
                memberPrivilege = memberPrivilegeService.getMemberPrivilege(1L);
            } else {
                memberPrivilege = memberPrivilegeService.getMemberPrivilege(11L);
            }

            Date firstDayOfMonth = DateUtils.getFirstDayOfMonth(new Date());
            Date lastDayOfMonth = DateUtils.getLastDayOfMonth(new Date());
            Long monthLikeNum = memberEquityService.memberEquityNum(getLoginUserId(), "喜欢我", firstDayOfMonth, lastDayOfMonth);
            if (Objects.equals(memberPrivilege.getHavaUnlimited(), (byte) 0) && Objects.equals(memberPrivilege.getStatus(), (byte) 1)) {
                if (monthLikeNum >= Long.parseLong(memberPrivilege.getPrivilegeNum())) {
                    throw exception(MEMBER_LIKE_NUM);
                }
            }
        }

        Long loginUserId = getLoginUserId();
        AppMemberLikeReqVO appMemberLikeReqVO = new AppMemberLikeReqVO();
        appMemberLikeReqVO.setIssue(createReqVO.getIssue());
        appMemberLikeReqVO.setReceive(createReqVO.getReceive());
        MemberLikeDO blindMemberLike = memberLikeService.getBlindMemberLike(appMemberLikeReqVO);
        if (Objects.nonNull(blindMemberLike)) {
            if (Objects.equals(loginUserId, Long.valueOf(blindMemberLike.getIssue()))) {
                return success(new AppExchangeReqVo());
            }

            BlindMemberUserDO user = blindMemberUserService.getMemberUser(Long.valueOf(createReqVO.getReceive()));
            if (Objects.isNull(user)){
                return error(401, "获取喜欢人的个人信息失败");
            }

            MemberLikeUpdateReqVO updateReqVO = new MemberLikeUpdateReqVO();
            updateReqVO.setId(blindMemberLike.getId());
            updateReqVO.setLikeEachother((byte) 1);
            memberLikeService.updateMemberLike(updateReqVO);
            blindNotifyMessageUtils.createLikeMessage(createReqVO);
            AppExchangeReqVo appExchangeReqVo = new AppExchangeReqVo();
            if (Objects.equals(Long.valueOf(createReqVO.getReceive()), loginUserId)) {
                appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getIssue()));
            } else {
                appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getReceive()));
            }

            appExchangeReqVo.setEachOther((byte) 1);
            appExchangeReqVo.setMatchAge(user.getAge());
            appExchangeReqVo.setMatchNickName(user.getNickname());
            appExchangeReqVo.setMatchAvatar(user.getAvatar());
            appExchangeReqVo.setOwnAvatar(memberUser.getAvatar());
            return success(appExchangeReqVo);
        }

        MemberEquityCreateReqVO memberEquityCreateReqVO = new MemberEquityCreateReqVO();
        memberEquityCreateReqVO.setUserId(getLoginUserId());
        memberEquityCreateReqVO.setEquityName("喜欢我");
        memberEquityCreateReqVO.setUsedBy(createReqVO.getReceive());
        memberEquityService.createMemberEquity(memberEquityCreateReqVO);
        Long memberLike = memberLikeService.createMemberLike(createReqVO);
        if (Objects.nonNull(memberLike)) {
            blindNotifyMessageUtils.createLikeMessage(createReqVO);
        }
        AppExchangeReqVo appExchangeReqVo = new AppExchangeReqVo();
        if (Objects.equals(Long.valueOf(createReqVO.getReceive()), loginUserId)) {
            appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getIssue()));
        } else {
            appExchangeReqVo.setUserId(Long.valueOf(createReqVO.getReceive()));
        }
        appExchangeReqVo.setEachOther((byte) 0);
        return success(appExchangeReqVo);
    }


    @GetMapping("/myQuantityStatistics")
    @Operation(summary = "我的信息 打招呼、喜欢我、看过我数量")
    public CommonResult<AppMyQuantityStatisticsVo> myQuantityStatistics() {

        AppMyQuantityStatisticsVo appMyQuantityStatisticsVo = new AppMyQuantityStatisticsVo();
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(loginUserId);
        if (Objects.isNull(memberUser)) {
            return error(401, "获取个人信息失败");
        }
        appMyQuantityStatisticsVo.setUserLevel(memberUser.getUserLevel());
        appMyQuantityStatisticsVo.setMemberEndTime(memberUser.getMemberEndTime());
        appMyQuantityStatisticsVo.setNickname(memberUser.getNickname());
        appMyQuantityStatisticsVo.setAvatar(memberUser.getAvatar());
        appMyQuantityStatisticsVo.setAuditAvatar(memberUser.getAuditAvatar());
        appMyQuantityStatisticsVo.setAuditStatus(memberUser.getAuditStatus());

        // 是否是会员
        appMyQuantityStatisticsVo.setHaveMember(memberUser.getHaveMember());

        boolean haveNameAuth = StringUtils.isNotEmpty(memberUser.getName()) && StringUtils.isNotEmpty(memberUser.getIdNumber());
        appMyQuantityStatisticsVo.setHaveNameAuth(haveNameAuth ? 1 : 0);
        appMyQuantityStatisticsVo.setLikeMeNum(memberLikeService.likeMeNum(loginUserId));
        appMyQuantityStatisticsVo.setSayHelloNum(memberSayhelloService.greeMeNum(loginUserId));
        appMyQuantityStatisticsVo.setSeeMeNum(memberSeemeService.seeMeNum(loginUserId));
        // 是否购买红娘
        int maker_num = memberStringingApiService.getSelectOne(loginUserId);
        appMyQuantityStatisticsVo.setIsMaker(maker_num > 0);
        int dis_num = memberStringingApiService.getIsMarker(loginUserId);
        appMyQuantityStatisticsVo.setDisMaker(dis_num > 0);
        appMyQuantityStatisticsVo.setAvatarAuth(memberUser.getAvatarAuth());
        ConstellationTestExportReqVO exportReqVO = new ConstellationTestExportReqVO();
        exportReqVO.setUserId(memberUser.getId());
        List<ConstellationTestDO> constellationTestList = constellationTestService.getConstellationTestList(exportReqVO);
        appMyQuantityStatisticsVo.setIsConstellationCommit(CollectionUtils.isNotEmpty(constellationTestList) ? (byte) 1 : (byte) 0);
        if (CollectionUtils.isNotEmpty(constellationTestList)){
            appMyQuantityStatisticsVo.setIsConstellationTest(constellationTestList.get(0).getStatus());
        }else {
            appMyQuantityStatisticsVo.setIsConstellationTest((byte) 0);
        }
        return success(appMyQuantityStatisticsVo);

    }

    @PostMapping("/forceMatchingUser")
    @Operation(summary = "强制匹配用户")
    public CommonResult<AppExchangeReqVo> forceMatchingUser(@Valid @RequestBody MemberEquityCreateReqVO createReqVO) {
        // 是否是会员验证
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO login = blindMemberUserService.getMemberUser(loginUserId);
        if (Objects.isNull(login)) {
            return error(401, "获取个人信息失败");
        } else {
            if (Objects.equals(login.getHaveMember(), (byte) 0)) {
                throw exception(MEMBER_FORCE_PAIRING_NOT_EXISTS);
            }

            Date firstDayOfMonth = DateUtils.getFirstDayOfMonth(new Date());
            Date lastDayOfMonth = DateUtils.getLastDayOfMonth(new Date());
            Long forceNum = memberEquityService.memberEquityNum(getLoginUserId(), "强制匹配", firstDayOfMonth, lastDayOfMonth);
            MemberPrivilegeDO memberPrivilege;
            if (Objects.equals(login.getUserLevel(), (byte) 1)) {
                memberPrivilege = memberPrivilegeService.getMemberPrivilege(1L);
            } else {
                memberPrivilege = memberPrivilegeService.getMemberPrivilege(11L);
            }

            if (Objects.equals(memberPrivilege.getHavaUnlimited(), (byte) 0) && Objects.equals(memberPrivilege.getStatus(), (byte) 1)) {
                if (forceNum >= Long.parseLong(memberPrivilege.getPrivilegeNum())) {
                    throw exception(FORCED_MATCHES_NUM);
                }
            }

            createReqVO.setUserId(getLoginUserId());
            Long memberEquity = memberEquityService.createMemberEquity(createReqVO);
            if (Objects.nonNull(memberEquity)) {
                blindNotifyMessageUtils.createForceMatchMessage(createReqVO, login);
            }
        }

        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(createReqVO.getMatchedId());
        if (Objects.isNull(memberUser)) {
            return error(401, "获取匹配人信息失败");
        }
        AppExchangeReqVo appExchangeReqVo = new AppExchangeReqVo();
        appExchangeReqVo.setUserId(createReqVO.getMatchedId());
        appExchangeReqVo.setMatchAge(memberUser.getAge());
        appExchangeReqVo.setMatchNickName(memberUser.getNickname());
        appExchangeReqVo.setMatchAvatar(memberUser.getAvatar());
        appExchangeReqVo.setEachOther((byte) 1);
        appExchangeReqVo.setOwnAvatar(login.getAvatar());
        return success(appExchangeReqVo);
    }

    /**
     * 相亲-获取当前会员用户手机号（加密）
     */
    @GetMapping("/getMobile")
    @Operation(summary = "获取当前会员用户的手机号")
    public CommonResult<JSONObject> getMobile() {
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(loginUserId);
        if (Objects.isNull(memberUser)) {
            return error(401, "获取用户手机号信息失败，请重新登录");
        }
        String mobile = memberUser.getMobile().substring(0, 3) + "****" + memberUser.getMobile().substring(7);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile", mobile);
        jsonObject.put("phone", memberUser.getMobile());
        return success(jsonObject);
    }


    /**
     * 相亲-获取当前会员用户手机号（加密）
     */
    @GetMapping("/checkMobile")
    @Operation(summary = "校验用户手机号是否正确")
    public CommonResult<Boolean> checkMobile(@RequestParam("mobile") String mobile) {
        Boolean t = false;
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(loginUserId);
        if (Objects.isNull(memberUser)) {
            return error(401, "校验手机号失败，您需要重新登录！");
        }
        // 去除空格和特殊字符
        String cleanNumber1 = mobile.replaceAll("[^0-9]", "");
        String cleanNumber2 = memberUser.getMobile().replaceAll("[^0-9]", "");
        if (cleanNumber2.equals(cleanNumber1)) {
            t = true;
            return success(t);
        } else {
            return error(500, "当前手机号验证失败，请重新输入！");
        }
    }

    /**
     * 补充个人信息
     * appMemberExchangeReqVOS 查出的结果
     * isSeeMe 是否是看过我 需要查打招呼
     * loginUserId 当前登陆人
     */
    public List<AppMemberExchangeReqVO> suppleMemberInformation(List<AppMemberExchangeReqVO> appMemberExchangeReqVOS, String isSeeMe, String loginUserId, Integer haveMember) {
        if (CollectionUtils.isEmpty(appMemberExchangeReqVOS)) {
            return new ArrayList<>();
        }
        List<AppMemberExchangeReqVO> exchangeReqVOS = new ArrayList<>();
        for (int i = 0; i < appMemberExchangeReqVOS.size(); i++) {
            AppMemberExchangeReqVO appMemberExchangeReqVO = appMemberExchangeReqVOS.get(i);
            String userId;
            if (Objects.equals(appMemberExchangeReqVO.getIssue(), loginUserId)) {
                userId = appMemberExchangeReqVO.getReceive();
            } else {
                userId = appMemberExchangeReqVO.getIssue();
            }
            if (StringUtils.isNotBlank(userId)) {

                BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(Long.valueOf(userId));
                if (Objects.nonNull(memberUser)) {
                    appMemberExchangeReqVO.setRecordId(appMemberExchangeReqVO.getId());
                    BeanUtils.copyProperties(memberUser, appMemberExchangeReqVO);
                    if (Objects.nonNull(appMemberExchangeReqVO.getPurchasCar())) {
                        appMemberExchangeReqVO.setPurchasCarName(DictFrameworkUtils.getDictDataLabel(BlindDictTypeConstants.PURCHASE_CAR, Integer.valueOf(appMemberExchangeReqVO.getPurchasCar())));
                    }
                    if (Objects.nonNull(appMemberExchangeReqVO.getPurchasHouse())) {
                        appMemberExchangeReqVO.setPurchasHouseName(DictFrameworkUtils.getDictDataLabel(BlindDictTypeConstants.PURCHASE_SITUATION, Integer.valueOf(appMemberExchangeReqVO.getPurchasHouse())));
                    }
                    if (StringUtils.isNotEmpty(appMemberExchangeReqVO.getMonthIncome())) {
                        appMemberExchangeReqVO.setMonthIncomeName(DictFrameworkUtils.getDictDataLabel(BlindDictTypeConstants.MATCH_INCOME, appMemberExchangeReqVO.getMonthIncome()));
                    }
                    //二级地区名
                    String areaId = memberUser.getAreaId();
                    String[] split = areaId.split(",");
                    if (split.length > 0) {
                        appMemberExchangeReqVO.setAreaName(AreaUtils.getAreaName(split[1]));
                    } else {
                        // 默认值：山东省淄博市张店区
                        String area = "370000,370300,370303";
                        String[] splits = area.split(",");
                        appMemberExchangeReqVO.setAreaName(AreaUtils.getAreaName(splits[1]));
                    }
                    appMemberExchangeReqVO.setAreaName(AreaUtils.getAreaName(split[1]));
                    appMemberExchangeReqVO.setDynamicNum(blindMemberMomentService.getBlindMemberMomentCount(Long.valueOf(userId)));
                    appMemberExchangeReqVO.setPhotoNum(blindMemberAlbumService.getBlindMemberAlbumCount(Long.valueOf(userId)));
                    appMemberExchangeReqVO.setHaveMate(haveMate(memberUser));
                    boolean haveNameAuth = StringUtils.isNotEmpty(memberUser.getName()) && StringUtils.isNotEmpty(memberUser.getIdNumber());
                    appMemberExchangeReqVO.setHaveNameAuth(haveNameAuth ? 1 : 0);
                    appMemberExchangeReqVO.setHaveMember(haveMember);
                    //从第三条开始往后模糊
                    if (Objects.equals(appMemberExchangeReqVO.getHaveMember(), 0)) {
                        if (i >= 3) {
                            appMemberExchangeReqVO.setHaveBlurry(Boolean.TRUE);
                        }
                    }
                    //如果是看过我 需要查询是否像我打过招呼
                    if (Objects.equals(isSeeMe, "1")) {
                        processSayHello(appMemberExchangeReqVO, appMemberExchangeReqVO.getReceive());
                    }
                    exchangeReqVOS.add(appMemberExchangeReqVO);
                }
            }
        }
        return exchangeReqVOS;
    }

    /**
     * 处理打招呼数据
     *
     * @param appMemberExchangeReqVO
     */
    private void processSayHello(AppMemberExchangeReqVO appMemberExchangeReqVO, String id) {
        AppMemberSayhelloReqVO appMemberSayhelloReqVO = new AppMemberSayhelloReqVO();
        appMemberSayhelloReqVO.setIssue(appMemberExchangeReqVO.getIssue());
        appMemberSayhelloReqVO.setReceive(appMemberExchangeReqVO.getReceive());
        MemberSayhelloDO blindMemberSayHello = memberSayhelloService.getBlindMemberSayHello(appMemberSayhelloReqVO);
        if (Objects.nonNull(blindMemberSayHello)) {
            if (Objects.equals(blindMemberSayHello.getIssue(), String.valueOf(getLoginUserId()))) {
                appMemberExchangeReqVO.setIGreetedHimBefore(1);
            }
            if (Objects.equals(blindMemberSayHello.getIssue(), String.valueOf(id))) {
                appMemberExchangeReqVO.setHeGreetedMeBefore(1);
            }
            appMemberExchangeReqVO.setSayHello(blindMemberSayHello.getSayHello().intValue());
        }
    }

    /**
     * 会员匹配度
     *
     * @param memberUser
     * @return
     */
    private boolean haveMate(BlindMemberUserDO memberUser) {
        BlindBasicSettingDO basicSetting = blindBasicSettingService.getBasicSetting(1L);
        Integer matchDegree;
        if (Objects.equals(memberUser.getHaveMember(), (byte) 1)) {
            matchDegree = basicSetting.getMatchUser();
        } else {
            matchDegree = basicSetting.getMatchNonUser();
        }
        BlindMemberUserDO blindMemberUserDO = blindMemberUserService.getMemberUser(getLoginUserId());
        return matchConditions(haveImSingle(blindMemberUserDO, memberUser), matchDegree);
    }

    /**
     * 判断我们是否匹配
     *
     * @param loginUser
     * @param memberUserUser
     * @return
     */
    private Integer haveImSingle(BlindMemberUserDO loginUser, BlindMemberUserDO memberUserUser) {
        Integer single = 0;
        String matchAge = loginUser.getMatchAge();
        if (StringUtils.isNotEmpty(matchAge) && Objects.nonNull(memberUserUser.getAge())) {
            List<String> ageList = MemberUserEnumUtil.matchAge(DictFrameworkUtils.getDictDataLabel(BlindDictTypeConstants.MATCH_AGE, matchAge));
            if (CollectionUtils.isEmpty(ageList)) {
                single++;
            } else {
                if (memberUserUser.getAge() >= Integer.parseInt(ageList.get(0))
                        || memberUserUser.getAge() <= Integer.parseInt(ageList.get(1))) {
                    single++;
                }
            }
        }


        String matchHeight = loginUser.getMatchHeight();
        if (StringUtils.isNotEmpty(matchHeight) && StringUtils.isNotEmpty(memberUserUser.getHeight())) {
            List<String> matchHeightList = MemberUserEnumUtil.matchHeight(DictFrameworkUtils.getDictDataLabel(BlindDictTypeConstants.MATCH_HEIGHT, matchHeight));
            if (CollectionUtils.isEmpty(matchHeightList)) {
                single++;
            } else {
                if (Integer.parseInt(memberUserUser.getHeight()) >= Integer.parseInt(matchHeightList.get(0))
                        || Integer.parseInt(memberUserUser.getHeight()) <= Integer.parseInt(matchHeightList.get(1))) {
                    single++;
                }
            }
        }
        if (Objects.equals(loginUser.getMatchIncome(), memberUserUser.getMonthIncome())) ;
        if (Objects.equals(loginUser.getMatchDrink(), memberUserUser.getDrink())) single++;
        if (Objects.equals(loginUser.getMatchEducation(), memberUserUser.getEducation())) single++;
        if (Objects.equals(loginUser.getMatchSmoker(), memberUserUser.getSmoker())) single++;
        if (Objects.equals(loginUser.getMatchWantChild(), memberUserUser.getWantChild())) single++;
        if (Objects.equals(loginUser.getMatchWithChild(), memberUserUser.getWithChild())) single++;
        if (Objects.equals(loginUser.getMatchWorkArea(), memberUserUser.getAreaId())) single++;
        if (Objects.equals(loginUser.getMatchMarriage(), memberUserUser.getMarriage())) single++;
        return single;
    }


    /**
     * 需要满足几个条件
     *
     * @param single
     * @param matchDegree
     */
    private boolean matchConditions(Integer single, Integer matchDegree) {
        Integer matchNum = matchDegree / 10;
        if (single > matchNum) {
            return true;
        }
        return false;
    }

    /**
     * 判断会员是否还有打招呼的次数-本月
     *
     * @return
     */
    public boolean getForceNum() {
        boolean t = true;
        // 是否是会员验证
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO login = blindMemberUserService.getMemberUser(loginUserId);

        Date firstDayOfMonth = DateUtils.getFirstDayOfMonth(new Date());
        Date lastDayOfMonth = DateUtils.getLastDayOfMonth(new Date());
        Long forceNum = memberEquityService.memberEquityNum(getLoginUserId(), "打招呼", firstDayOfMonth, lastDayOfMonth);
        Byte userLevel = login.getUserLevel();
        MemberPrivilegeDO memberPrivilege;
        if (Objects.equals(userLevel, (byte) 1)) {
            memberPrivilege = memberPrivilegeService.getMemberPrivilege(2L);
        } else {
            memberPrivilege = memberPrivilegeService.getMemberPrivilege(12L);
        }

        if (Objects.equals(memberPrivilege.getHavaUnlimited(), (byte) 0) && Objects.equals(memberPrivilege.getStatus(), (byte) 1)) {
            if (forceNum >= Long.parseLong(memberPrivilege.getPrivilegeNum())) {
                t = false;
            }
        }
        return t;
    }

}




